import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:graphic/graphic.dart';
import 'package:intl/intl.dart';
import 'package:simudata_display/app/data/protobuf/simu_message.pb.dart';

import '../controllers/chart_view_controller.dart';

class ChartViewView extends GetView<ChartViewController> {
  const ChartViewView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ChartViewController controller = Get.find<ChartViewController>();
    return Scaffold(
        appBar: AppBar(
          title: const Text('ChartViewView'),
          centerTitle: true,
        ),
        body: GetBuilder<ChartViewController>(
          builder: controller.simuDatas.isEmpty
              ? (_) => const Center(
                    child: Text(
                      'No data',
                      style: TextStyle(fontSize: 20),
                    ),
                  )
              : (_) => Container(
                  padding: const EdgeInsets.all(10),
                  child: Chart(
                    data: controller.simuDatas,
                    rebuild: false,
                    changeData: true,
                    variables: {
                      't': Variable(
                        accessor: (SimuData d) =>
                            DateTime.fromMillisecondsSinceEpoch(
                                d.timestamp.toInt()),
                        scale: TimeScale(
                          tickCount: 5,
                          formatter: (time) =>
                              DateFormat('MM-dd HH:mm:ss').format(time),
                        ),
                      ),
                      'v': Variable(accessor: (SimuData d) => d.value),
                      'group':
                          Variable(accessor: (SimuData d) => d.id.toString())
                    },
                    marks: [
                      LineMark(
                        position: Varset('t') * Varset('v') / Varset('group'),
                        shape: ShapeEncode(value: BasicLineShape(smooth: true)),
                        size: SizeEncode(value: 0.5),
                        color: ColorEncode(
                          variable: 'group',
                          values: Defaults.colors10,
                          updaters: {
                            'groupMouse': {
                              false: (color) => color.withAlpha(100)
                            },
                            'groupTouch': {
                              false: (color) => color.withAlpha(100)
                            },
                          },
                        ),
                      ),
                    ],
                    coord: RectCoord(
                      horizontalRangeUpdater: Defaults.horizontalRangeEvent,
                    ),
                    axes: [Defaults.horizontalAxis, Defaults.verticalAxis],
                  )),
        ));
  }
}
